﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{ await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml"); }
    @{ await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml"); }
    <script type="text/javascript" src="~/lib/echarts/extension/dataTool.js?v=@DateTime.Now.Ticks" asp-append-version="true"></script>

    <link href="/css/ReportYield.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>ReportYield</title>

    <style type="text/css">
        .hover-image {
            display: none;
            position: absolute;
            top: 20px;
            left: 0;
            width: 35vw;
            border: 1px solid #ccc;
            background: #fff;
            z-index: 999;
        }

        .warn-flag:hover .hover-image {
            display: block;
        }
        /*选项卡*/
        .tab {
            overflow: hidden;
            width: 100%;
            height: 0.6rem;
            padding-left: 0.1rem;
            padding-right: 0.2rem;
        }

        .tab button {
            background-color: inherit;
            float: left;
            border: none;
            outline: none;
            cursor: pointer;
            /*padding: 14px 16px;*/
            font-size: 0.16rem;
            padding: 0.14rem 0.16rem;
            transition: 0.3s;
            border-bottom: 2px solid #ffffff;
        }

        .tab button:hover {
            background-color: rgba(0, 128, 204, 0.25);
        }

        .tab button.active {
            color: white;
            background-color: rgba(0, 128, 204, 0.15);
            border-bottom: 2px solid #0080cc;
        }

        .tabcontent {
            padding: 6px 12px;
            border-top: none;
            width: 100%;
            height: 4.6rem;
        }

        .remark {
            float: right;
        }

        .required {
            color: red;
            font-weight: bolder;
        }

    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="ModalShow('modal-msg')">@Label.Datum@Label.Maintain</a>
                                <a class="menudropdown" onclick="TestDataExport('TestData')">@Label.Data@Label.Export</a>
                                <a class="menudropdown" onclick="YieldReportExport('YieldReport')">@Label.Report@Label.Export</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border">
                    <div class="title">
                        <span class="warn-flag" style="color:red; position: relative;">ℹ️<img src="../images/lot.png?v=@DateTime.Now.Ticks" class="hover-image" /></span>
                        <label>@Html.Raw(Label.Process + @Label.Yield + @Label.Report)</label>
                    </div>
                    <div id="board" class="chart">
                        <div class="query">
                            <button class="btn btn-primary  btn-sm col-md-12" type="button" onclick="$('.modal').fadeIn();">@Html.Raw(Label.Query + @Label.Where)</button>
                        </div>
                        <div id="table-container">
                            <table class="DataSheet" border="1" style="width: 100%; height: 100%;">
                                <thead>
                                    <tr>
                                        <th>Station</th>
                                        <th>Input</th>
                                        <th>Output</th>
                                        <th>PrimeYield</th>
                                        <th>FinalYield</th>
                                        <th>FailureMode</th>
                                        <th>PrimeReject</th>
                                        <th>RetestPass</th>
                                        <th>PrimeRejectRate</th>
                                        <th>FinalRejectRate</th>
                                    </tr>
                                </thead>
                                <tbody id="yield_tbody"></tbody>
                                <tfoot>
                                    <tr>
                                        <th id="sum" colspan="3"></th>
                                        <th id="primeyield"></th>
                                        <th id="finalyield"></th>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="center-cen fl">
                <div class="cen-top rightTop border">
                    <div class="title"><label>@Html.Raw(Label.Tests + Label.Item + Label.Fail + Label.Plato)</label></div>
                    <div id="chart1" class="chart"></div>
                </div>
                <div class="cen-bottom rightTop border">
                    <div class="tab">
                        <button class="tablinks active" onclick="OpenTab(event,'cen-bottom','Tab1',GetPrimeFailRate)">PrimeFailRate</button>
                        <button class="tablinks" onclick="OpenTab(event,'cen-bottom','Tab1',GetFinalFailRate)">FinalFailRate</button>
                    </div>
                    <div id="Tab1" class="chart" style="padding: 0rem 0.2rem;">
                        <div class="cpk_table_id">
                            <table class="cpk_table">
                                <thead>
                                    <tr>
                                        <th>TESTER</th>
                                        <th>INPUT </th>
                                        <th>PASS</th>
                                        <th>FAIL</th>
                                        <th>FAILURE</th>
                                    </tr>
                                </thead>
                                <tbody id="tester_body">
                                    <tr>
                                        <td></td>
                                        <td></td>
                                        <td></td>
                                        <td></td>
                                        <td></td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th>总计</th>
                                        <td id="sum_input"></td>
                                        <td id="sum_pass"></td>
                                        <td id="sum_fail"></td>
                                        <td id="failure"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    <!-- 模态框 -->
    <div class="modal">
        <div class="modal-content family">
            <span class="close" onclick="ModalClose('modal')">×</span>
            <p id="Item" class="modal-title">@Html.Raw(Label.Query + Label.Where)</p>
            <br>
            <div class="form-flex">
                <p><label for="Area">Area:</label><span class="remark required">*</span></p>
                <select id="cmb_area_type" name="Area" placeholder="select Area">
                    <option value="DG">@Label.DG</option>
                    <option value="AMT">@Label.AMT</option>
                </select>
                <p><label for="Projectcode">ProjectCode:</label><span class="remark required">*</span></p>
                <select id="cmb_proj_code" name="Projectcode" placeholder="select Projectcode">
                    <option value="">@Label.PleaseSelect</option>
                </select>
                <p><label for="ProdType">@Html.Raw(Label.Data + Label.Type):(@Html.Raw(Label.Fresh + Label.Lot)="P-00";@Html.Raw(Label.Rework + Label.Lot)!="P-00";@Html.Raw(Label.RMA) Lot="Rxxx")</label><span class="remark required">*</span></p>
                <select id="cmb_prod_type" name="ProdType" placeholder="select prodtype">
                    <option value="">@Label.PleaseSelect</option>
                    <option value="ALL">@Label.ALL</option>
                    <option value="Normal">@Label.Fresh</option>
                    <option value="Rework">@Label.Rework</option>
                    <option value="RMA">@Label.RMA</option>
                </select>
                <p><label for="partnumber">PartNumber:</label><span class="remark">*</span></p>
                <textarea id="text_partnumber" class="text" rows="4" cols="50" placeholder="PartNumber"></textarea>
                <p><label for="sn">SN:</label><span class="remark Required">*</span></p>
                <textarea id="text_sn" class="text" rows="4" cols="50" placeholder="SN"></textarea>
                <p>
                    <span class="exampleInputProject tle">@Html.Raw(Label.Time):</span>
                    <input type="date" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time">
                    <span class="exampleInputProject tle">@Label.To</span>
                    <input type="date" id="enddate" name="enddate" placeholder="@Label.Start@Label.End">
                    <span class="remark required">*</span>
                </p>
                <button id="btn_query" type="submit" style="font-weight: bold; height:0.5rem;" onclick="Getdata()">@Html.Raw(Label.Query)</button>
            </div>
        </div>
    </div>

    <!-- 模态框 -文件下载上传 -->
    <div class="modal-msg">
        <div class="modal-content family">
            <span class="close" onclick="ModalClose('modal-msg')">×</span>
            <p id="Item" class="modal-title">@Html.Raw(Label.Fail + Label.Message + Label.Maintain)</p>
            <br>
            <div class="form-flex">
                <label for="projcode">projcode:</label>
                <select id="projcode" name="projcode" placeholder="select projcode"></select>
                <label for="process">process:</label>
                <select id="process" name="process" placeholder="select process"></select>
                <label>
                    <span><label><button type="submit" style="background-color: #49c5ce;" onclick="TestFailGroupExport()"><span><img src="/images/ProcessCapacity/Excel.ico" alt="Excel" class="icon"></span>生成Excel模板</button></label></span>
                    <span id="export"></span>
                </label>
                <span>
                    <label>@Html.Raw(Label.Import + Label.Template):</label>&nbsp;
                    <span><input type="file" id="Template" name="Template" style="width:calc(100% - 0.78rem)" placeholder="Enter your Process"></span>
                </span>
                <label for="message">message:</label>
                <input type="text" id="message" name="message" placeholder="Enter your message">
                <button type="submit" style="font-weight: bold; height:0.5rem;" onclick="UploadExcel()">Submit</button>
            </div>
        </div>
    </div>
    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
            });
            function numberToUpperCase(number) {
                var uppercaseMonths = ['一月', '二月', '三月', '四月', '五月', '六月','七月', '八月', '九月', '十月', '十一月', '十二月'];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html("@Html.Raw(Label.Board_TestItemAnalysis)");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear(); //年
                var myMonth = myDate.getMonth() + 1; //月
                var myToday = myDate.getDate(); //日
                var myDay = myDate.getDay(); //星期
                var myHour = myDate.getHours(); //小时
                var myMinute = myDate.getMinutes(); //分钟
                var mySecond = myDate.getSeconds(); //秒数
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);

            //设置全屏
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    //判断浏览器设备类型
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {       //兼容火狐
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {    //兼容谷歌
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {        //兼容IE
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit+Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });
            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                $('#enddate').val('');
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                //$('#enddate').attr('min', $(this).val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                var maxDate = new Date(startDate);
                maxDate.setMonth(maxDate.getMonth() + 1);
                if (endDate > maxDate) {
                    $('#enddate').val('');
                    alert('查询范围不能超过一个月！');
                } else {
                    //$('#startdate').attr('max', $(this).val());
                    endDate.setDate(endDate.getDate() - 1);
                    var maxStartDate = endDate.toISOString().split('T')[0];
                    $('#startdate').attr('max', maxStartDate);
                    if (startDate > endDate) {
                        $('#startdate').val($(this).val());
                    }
                }
            });

        });

        //初始化图表
        var memachinetype;
        var chartIds = ['chart1'];
        function echartsautomatic() {
            var charts = [];
            chartIds.forEach(function (chartId) {
                var chart = echarts.init(document.getElementById(chartId));
                charts.push(chart);
            });
            window.onresize = function () {
                charts.forEach(function (chart) {
                    chart.resize();
                });
            };
        }

        function ModalClose(modalname) {
            var close = document.getElementsByClassName(modalname);
            $(close).fadeOut();
        }

        //Tab页签定时切换
        var Tabtimer;
        function TabInterval() {
            clearInterval(Tabtimer);
            //每隔5m执行一次
            Tabtimer = setInterval(function () {
                var endDate = new Date($("#enddate").val());
                if (endDate > new Date()) {
                    Getdata();
                    echartsautomatic();
                }
            }, 10 * 60 * 1000);
        }

        $(function () {
            var startDate = new Date();
            startDate.setDate(startDate.getDate());
            var endDate = new Date();
            endDate.setDate(endDate.getDate() + 1);
            $('#startdate').val(startDate.toISOString().split('T')[0]);
            $('#enddate').val(endDate.toISOString().split('T')[0]);

            var projectsele = $("#cmb_proj_code");
            loadData(projectsele, api + '/ReportAction/GetProjCode', true);

            var pam = {};
            var projcode = $("#projcode");
            var process = $("#process");
            loadData(projcode, api + '/ReportAction/GetProjCode', false);
            projcode.change(function () {
                pam.proj_code = $(this).val();
                loadData(process, api + '/ReportAction/GetTestProcess', false);
            });
            //$("#cmb_proj_code").prop('selectedIndex', 1);
            $('#cmb_area_type').val('DG');
            $('#cmb_proj_code').val('NCCSAD').trigger('change');
            $("#cmb_prod_type").prop('selectedIndex', 1);
            Getdata();
            function loadData(selectElement, url, boolean) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: pam,
                    async: false,
                    dataType: "json",
                    success: function (data) {
                        selectdata = data.ReturnData;
                        selectElement.empty();
                        if (selectdata.length <= 0) {
                            var option = "<option>@Html.Raw(Label.No+Label.Correlation+Label.Data)</option>";
                            selectElement.append(option);
                            return;
                        }
                         if (boolean) {
                            selectElement.append("<option value=''>@Html.Raw(Label.PleaseSelect)...</option>");
                        } else {
                            selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                        }
                        $.each(selectdata, function (key, value) {
                            selectElement.append($('<option>', {
                                value: value.value,
                                text: value.text
                            }));
                        });
                    }
                });
            }
        });

        function stateselected() {
            var state = false;
            if ($('#cmb_proj_code').prop('selectedIndex') > 0 && $('#cmb_prod_type').prop('selectedIndex') > 0 && $("#startdate").val() && $("#enddate").val()) {
                state = true;
            }
            return state;
        }

        /*Tab切换*/
        function OpenTab(evt, panle, id, echar_name, itemindex = -1) {
            var i, tablinks;
            tablinks = document.getElementsByClassName(panle)[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
            }
            evt.currentTarget.className += " active";
            //注销eacharts
            let chart = echarts.init(document.getElementById(id));
            chart.dispose();
            /*TabItem 页签滚动*/
            if (itemindex > -1) {
                var listContainer = document.getElementById("listContainer");
                var listItem = listContainer.children[itemindex];
                var scrollContainer = document.getElementById("scrollContainer");
                // 计算要滚动的距离
                var scrollLeft = listItem.offsetLeft - scrollContainer.offsetLeft;
                // 滚动到指定位置
                //scrollContainer.scrollLeft = scrollLeft;
                scrollContainer.scrollTo({
                    left: scrollLeft,
                    behavior: "smooth",
                });
            }
            /*委托事件*/
            if (!memachinetype) {
                echar_name(id);
            }
            else {
                GetToDayMeMachine(id);
            }
            echartsautomatic();
        }

        var chartdata;
        var Getdata = function () {
            if (stateselected()) {
                boarddata();
                //echartsautomatic();
                //TabInterval();
            }
            else {
                alert("@Html.Raw(Label.PleaseSelect+Label.Required+Label.Where+Label.Item)");
            }
        }

        var ModalShow = function (type) {
            $("." + type+"").fadeIn();
        }

        /*导出生产数据*/
        var TestDataExport = function (type) {
            if (stateselected()) {
                ExportType = type;
                var formData = new FormData();
                formData.append('type', ExportType);
                formData.append('prodtype', $('#cmb_prod_type').val());
                formData.append('proj_code', $('#cmb_proj_code').val());
                formData.append('process_id', "ALL");
                formData.append('partnumber', $('#text_partnumber').val() == null ? "ALL" : $('#text_partnumber').val());
                formData.append('sn', $('#text_sn').val() == null ? "ALL" : $('#text_sn').val());
                formData.append('start_time', $("#startdate").val());
                formData.append('end_time', $("#enddate").val());
                formData.append('area', $('#cmb_area_type').val());
                var url = api + "/Dashboard/TestDataToExcel";
                PostExportToExcel(url, formData);
                alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
            }
            else {
                alert("请先查询^_^")
            }
        }

        //报表导出
        var YieldReportExport = function (type) {
            var formData = new FormData();
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('process_id', "ALL");
            formData.append('prodtype', $('#cmb_prod_type').val());
            formData.append('start', $("#startdate").val());
            formData.append('end', $("#enddate").val());
            formData.append('type', type);
            formData.append('area', $('#cmb_area_type').val());
            ExportType = type;
            var url = api + "/ReportAction/YieldReportToExcel";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }

        //POST 参数不固定 导出
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }

        var ExportType;
        var TestFailGroupExport = function () {
            ExportType = "TestFailGroup";
            var pam = {
                type: ExportType,
                proj_code: $('#projcode').val() == "" ? "ALL" : $('#projcode').val(),
                product_code: 'ALL',
                process_code: $('#process').val() == null ? "ALL" : $('#process').val()
            };
            var url = api + "/Dashboard/ExportToExcel?" + $.param(pam);
            ExportToExcel(url);
        }

        //上传
        var UploadExcel = function () {
            var fileInput = document.getElementById("Template");
            var file = fileInput.files[0];
            var formData = new FormData();
            formData.append("file", file);
            //formData.append("type", uploadType);
            formData.append("type", "TestFailGroup");
            $.ajax({
                type: "POST",
                //url: "http://localhost:44304/Dashboard/UploadExcel",
                url: api + "/Dashboard/UploadExcel",
                enctype: 'multipart/form-data',
                data: formData,
                async: false,
                processData: false,// 禁止将数据转换为查询字符串
                contentType: false,// 禁止设置请求头的Content-Type
                crossDomain: true,
                success: function (data) {
                    if (data.Success) {
                        alert("successfully");
                        //$('#product').empty();
                        //$('#process').empty();
                        $("#Template").val('');
                        $("#message").val('');
                        $(".modal-msg").fadeOut();
                    }
                }
            });

        };

        //导出
        var ExportToExcel = function (url) {
            //var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            /*
            var formData = new FormData();
            formData.append('CL_TYPE', $("#cmb_classtype").val());
            xhr.send(formData);
            */
            xhr.send();
        }

        //报表
        var boarddata = function () {
            $('#btn_query').prop('disabled', true);
            $("#yield_tbody, #sum, #primeyield, #finalyield").empty();
            var header_key = {
                partnumber: $('#text_partnumber').val(),
                sn: $('#text_sn').val(),
                starttime: $("#startdate").val(),
                endtime: $("#enddate").val(),
                area: $('#cmb_area_type').val()
            };
            var pam = {};
            pam.type = $('#cmb_prod_type').val();
            pam.proj_code = $('#cmb_proj_code').val();
            pam.header_key = JSON.stringify(header_key);
            $.ajax({
                type: "POST",
                url: api + "/ReportAction/GetTestYield",
                data: pam,
                dataType: "json",
                success: function (data) {
                    $('#btn_query').prop('disabled', false);
                    $("#yield_tbody, #sum, #primeyield, #finalyield").empty();
                    chartdata = data.ReturnData;
                    platoChart();
                    //primeyieldChart();
                    var table = "";
                    var primeyield, finalyield;
                    if (chartdata.Table.length > 0) {
                        ModalClose('modal');
                    }
                    for (var i = 0; i < chartdata.Table.length; i++) {
                        var zebracro = i % 2;
                        if (chartdata.Table[i].ROW_ID && parseInt(chartdata.Table[i].ROW_ID) > 0) {
                            table += '<tr ' + (zebracro == 0 ? 'class="zebracro"' : '') + '>'
                                + '<td class="tabletd" rowspan=' + chartdata.Table[i].ROWSPAN + '>' + chartdata.Table[i].PROCESS_ID + '</td>'
                                + '<td class="tabletd" rowspan=' + chartdata.Table[i].ROWSPAN + '>' + chartdata.Table[i].INPUT_QTY + '</td>'
                                + '<td class="tabletd" rowspan=' + chartdata.Table[i].ROWSPAN + '>' + chartdata.Table[i].OUTPUT_QTY + '</td>'
                                + '<td class="tabletd" rowspan=' + chartdata.Table[i].ROWSPAN + '>' + chartdata.Table[i].PRIME_YIELD + '</td>'
                                + '<td class="tabletd" rowspan=' + chartdata.Table[i].ROWSPAN + '>' + chartdata.Table[i].FINAL_YIELD + '</td>'
                                + '<td>' + chartdata.Table[i].FAILURE_MODE + '</td>'
                                + '<td class="tabletd">' + chartdata.Table[i].PRIME_REJECT + '</td>'
                                + '<td class="tabletd">' + chartdata.Table[i].RETEST_PASS + '</td>'
                                + '<td class="tabletd">' + chartdata.Table[i].PRIME_REJECT_RATE + '</td>'
                                + '<td class="tabletd">' + chartdata.Table[i].FINAL_REJECT_RATE + '</td>'
                                + '</tr>';
                            var primeyieldFloat = parseFloat(chartdata.Table[i].PRIME_YIELD.substring(0, chartdata.Table[i].PRIME_YIELD.indexOf("%"))) / 100;
                            var finalyieldFloat = parseFloat(chartdata.Table[i].FINAL_YIELD.substring(0, chartdata.Table[i].FINAL_YIELD.indexOf("%"))) / 100;
                            if (!(primeyield)) {
                                primeyield = (primeyieldFloat > 0 ? primeyieldFloat : 1);
                            }
                            else {
                                primeyield = primeyield * (primeyieldFloat > 0 ? primeyieldFloat : 1);
                            }
                            if (!(finalyield)) {
                                finalyield = (finalyieldFloat > 0 ? finalyieldFloat : 1);
                            }
                            else {
                                finalyield = finalyield * (finalyieldFloat > 0 ? finalyieldFloat : 1);
                            }
                        }
                        else {
                            table += '<tr ' + (zebracro == 0 ? 'class="zebracro"' : '') + '>'
                                + '<td>' + chartdata.Table[i].FAILURE_MODE + '</td>'
                                + '<td class="tabletd">' + chartdata.Table[i].PRIME_REJECT + '</td>'
                                + '<td class="tabletd">' + chartdata.Table[i].RETEST_PASS + '</td>'
                                + '<td class="tabletd">' + chartdata.Table[i].PRIME_REJECT_RATE + '</td>'
                                + '<td class="tabletd">' + chartdata.Table[i].FINAL_REJECT_RATE + '</td>'
                                + '</tr>';
                        }
                    }
                    $('#yield_tbody').html(table);
                    $("#sum").text("@Html.Raw(Label.Summary)");
                    $('#primeyield').html(parseFloat((primeyield * 100).toFixed(2)) + "%");
                    $('#finalyield').html(parseFloat((finalyield * 100).toFixed(2)) + "%");
                }
            });
        };

        //chart
        var primedt;
        var finaldt;
        var plato_optionloop;
        function platoChart() {
            var chart = document.getElementById("chart1");
            var myChart = echarts.init(chart);
            var item = [];
            var itemvaule = [];
            var linevaule = [];
            var lastvaule;
            var data =JSON.parse(chartdata.Table1[0].FINAL_PLATO_JSON);
            if (data) {
                for (var i = 0; i < data.length; i++) {
                    item.push(data[i].FAILURE_MODE);
                    itemvaule.push(data[i].FINAL_REJECT_RATE);
                    if (i == 0) {
                        lastvaule = data[i].PLATO_VAULE;
                        linevaule.push(data[i].PLATO_VAULE);
                    } else {
                        lastvaule = lastvaule + data[i].PLATO_VAULE;
                        linevaule.push(lastvaule.toFixed(2));
                    }
                }
            };
            var itemvaulemax = Math.max.apply(null, itemvaule);
            option = {
                textStyle: {
                    color: '#fff',
                    fontSize: '0.14rem'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: 'white'
                        }
                    }
                },
                grid: {
                    top: '10%',
                    left: '7%',
                    right: '8%',
                    width: '85%'
                },
                xAxis: [
                    {
                        type: 'category',
                        data: item,
                        axisLabel: {
                            show: true,
                            interval: item.length > 30 ? Math.floor(item.length / 30) : 0,
                            rotate: 45,
                            textStyle: {
                                color: 'white',
                                fontSize: '0.12rem'
                            }
                        },
                        axisPointer: {
                            type: 'shadow'
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: 'FinalRejectRate',
                        min: 0,
                        max: Math.ceil(itemvaulemax),
                        interval: Math.ceil(itemvaulemax) / 5,
                        scale: true,
                        splitLine: { show: false },
                        axisTick: {
                            show: true
                        },
                        axisLine: {
                            show: true
                        },
                        axisLabel: {
                            show: true,
                            formatter: '{value} %',
                            textStyle: {
                                color: 'white',
                                fontSize: '0.12rem'
                            }
                        }
                    },
                    {
                        type: 'value',
                        name: 'Proportion',
                        min: 0,
                        max: 100,
                        interval: 20,
                        scale: true,
                        splitLine: { show: false },
                        axisTick: {
                            show: true
                        },
                        axisLine: {
                            show: true
                        },
                        axisLabel: {
                            show: true,
                            formatter: '{value} %',
                            textStyle: {
                                color: 'white',
                                fontSize: '0.12rem'
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: 'Failure Rate',
                        type: 'bar',
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                                    offset: 0,
                                    color: "#009AFD"
                                }, {
                                    offset: 0.8,
                                    color: "#33DAFF"
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                            }
                        },
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + ' %';
                            }
                        },
                        data: itemvaule
                    },
                    {
                        name: 'Proportion',
                        type: 'line',
                        yAxisIndex: 1,
                        itemStyle: { normal: { color: '#00C598 ' } },
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + ' %';
                            }
                        },
                        data: linevaule
                    }
                ]
            };
            myChart.setOption(option);
            window.addEventListener('resize', function () {
                myChart.resize();
            });
            myChart.on('click', function (params) {
                primedt = chartdata.Table7.filter(item => item.FAILURE_MODE === params.name);
                finaldt = chartdata.Table8.filter(item => item.FAILURE_MODE === params.name);
                GetPrimeFailRate("Tab1");
            });
            if (plato_optionloop) {
                //plato_optionloop.clearLoop();
                plato_optionloop = null;
            }
            plato_optionloop = tools.loopShowTooltip(echarts.init(chart), option, { loopSeries: true });
            primedt = chartdata.Table7;
            finaldt = chartdata.Table8;
            //GetPrimeFailRate("Tab1");
        };

        var SetFailRateList = function (data) {
            $("#Tab1").empty();
            var tbody = "";
            for (var i = 0; i < data.length; i++) {
                tbody += `<tr><td>${data[i].TESTER}</td><td>${data[i].INPUT}</td><td>${data[i].PASS}</td><td>${data[i].ABORT}</td><td>${data[i].FAIL}</td><td>${data[i].FAILURE}</td></tr>`
            }
            var sum_input = data.reduce((sum, item) => sum + item.INPUT, 0);
            var sum_pass = data.reduce((sum, item) => sum + item.PASS, 0);
            var sum_fail = data.reduce((sum, item) => sum + item.FAIL, 0);
            var sum_abort = data.reduce((sum, item) => sum + item.ABORT, 0);
            var failure = parseFloat((parseInt(sum_fail) / (parseInt(sum_input) + parseInt(sum_abort)) * 100).toFixed(2)) + "%";
            var tfoot = `<tr><th>总计</th><td id="sum_input">${sum_input}</td><td id="sum_pass">${sum_pass}</td><td id="sum_abort">${sum_abort}</td><td id="sum_fail">${sum_fail}</td><td id="failure">${failure}</td></tr>`;
            var table = `<div class="cpk_table_id"><table class="cpk_table"><thead><tr><th>TESTER</th><th>INPUT </th><th>PASS</th><th>ABORT</th><th>FAIL</th><th>FAILURE</th></tr></thead><tbody id="tester_body">${tbody}</tbody><tfoot>${tfoot}</tfoot></table></div>`;
            $('#Tab1').html(table);
        }

        var GetPrimeFailRate = function (id) {
            var data = primedt;
            SetFailRateList(data);
        }

        var GetFinalFailRate = function (id) {
            var data = finaldt;
            SetFailRateList(data);
        }


    </script>
</body>
</html>
